package com.ruoyi.web.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.ruoyi.core.entity.BaseEntity;
import com.ruoyi.web.context.RequestContextHolder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;

import java.sql.SQLException;
import java.util.Date;
import java.util.Objects;

/**
 * @author wanghao 913351190@qq.com
 * @create 2023/10/8 14:36
 */
public class DefaultMetaObjectInterceptor implements InnerInterceptor {
    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        if (Objects.nonNull(parameter) && parameter instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) parameter;
            SqlCommandType commandType = ms.getSqlCommandType();
            if (SqlCommandType.INSERT.equals(commandType)) {

                fillInsertColumns(baseEntity);


            } else if (SqlCommandType.UPDATE.equals(commandType)) {

                fillUpdateColumns(baseEntity);


            }

        }
        InnerInterceptor.super.beforeUpdate(executor, ms, parameter);
    }

    private void fillInsertColumns(BaseEntity baseEntity) {
        try {
            Date now = new Date();

            baseEntity.setCreateTime(now);
            baseEntity.setUpdateTime(now);
            baseEntity.setCreateBy(RequestContextHolder.currentUserId());
            baseEntity.setUpdateBy(RequestContextHolder.currentUserId());
            baseEntity.setCreateDept(RequestContextHolder.currentDeptId());

        } catch (Throwable e) {
            e.printStackTrace();
            //ignore
        }
    }

    private void fillUpdateColumns(BaseEntity baseEntity) {
        try {
            Date now = new Date();

            baseEntity.setCreateTime(null);
            baseEntity.setUpdateTime(now);
            baseEntity.setCreateBy(null);
            baseEntity.setUpdateBy(RequestContextHolder.currentUserId());
            baseEntity.setCreateDept(null);
        } catch (Throwable e) {
            e.printStackTrace();
            //ignore
        }
    }
}
